package com.telecom.service.impl;

import com.telecom.common.convention.errorcode.BaseErrorCode;
import com.telecom.common.convention.exception.ClientException;
import com.telecom.mapper.UserMapper;
import com.telecom.pojo.dto.admin.employee.EmployeeLoginDTO;
import com.telecom.pojo.entity.User;
import com.telecom.pojo.vo.admin.employee.EmployeeLoginVO;
import com.telecom.service.EmployeeService;
import com.telecom.common.utils.JwtUtils;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 员工服务实现类
 */
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    
    @Resource
    JwtUtils jwtUtils;
    @Resource
    UserMapper userMapper;
    
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO loginRequest) {
        log.info("管理员登录，用户名：{}", loginRequest.getUsername());
        
        // 1. 根据用户名查询用户信息
        User user = userMapper.findByUsername(loginRequest.getUsername());
        if (user == null){
            throw new ClientException("用户名或密码错误", BaseErrorCode.CLIENT_ERROR);
        }

        // 2. 验证用户名和密码
        String password = loginRequest.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            throw new ClientException("用户名或密码错误", BaseErrorCode.CLIENT_ERROR);
        }
        
        // 3. 检查是否为管理员
        if (user.getRole() == null || user.getRole() != 1) {
            throw new ClientException("非管理员账号，无法登录", BaseErrorCode.FORBIDDEN);
        }

        // 4. 检查用户状态
        if (!user.getIsEnabled()) {
            throw new ClientException("账号已被禁用", BaseErrorCode.FORBIDDEN);
        }
        
        // 生成JWT Token
        String token = jwtUtils.generateToken(user.getId(), user.getUsername(), user.getRole());
        
        EmployeeLoginVO response = new EmployeeLoginVO();
        response.setToken(token);
        response.setId(user.getId());
        response.setUserName(user.getUsername());
        
        log.info("管理员登录成功，用户ID：{}", user.getId());
        return response;
    }

}